"""
  Copyright (c) 2024 Northeastern University (China)
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
"""
import json
import os


class File:
    """
    该类中的函数为对文件的操作函数
    """

    """
    读取文本文件
    """
    @staticmethod  # 设置静态方法
    def read_txt(self, path):
        element_list = []
        with open(path, 'r', encoding='utf-8') as f:
            for line in f.readlines():
                element = line.strip()  # 把末尾的‘\n'删掉
                element_list.append(element)
            # f.close()  # 用with 关键字代开的文件，python在with语句结束后，默认关闭的
        return element_list

    @staticmethod  # 设置静态方法
    def write_txt(self, element_list, path):
        with open(path, 'w', encoding='utf-8') as f:
            for element in element_list:
                try:
                    f.write(element + "\n")
                except UnicodeError:
                    continue

    """
    读取json文件
    """
    @staticmethod
    def read_json(self, path):  # 读取json文件
        try:
            with open(path, "r", encoding='utf-8') as f:
                dicts = json.load(f)
                if dicts is None:  # 初次读取json文件为空，实例化一个list
                    dicts = []
                return dicts
        except json.decoder.JSONDecodeError:  # 读取的json文件必须存在且内容不能为空，否则会报错
            print("empty!")

    @staticmethod
    def write_json(self, dict_list, path):
        # indent 超级好用，格式化保存字典，默认为None，小于0为零个空格
        with open(path, 'w', encoding='utf-8') as f:
            f.write(json.dumps(dict_list, indent=4))

    """
    获取指定路径中的全部文件
    """
    @staticmethod
    def get_all_file(self, path):
        file_list = []
        for root, dirs, files in os.walk(path):
            for name in files:
                file_list.append(os.path.join(root, name))
        return file_list


